<?php
/**
 * @package  Guggenheim
 * @subpackage	Collections
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

require_once $_SERVER["DOCUMENT_ROOT"] . '/../lib/DataLayer.php';
require_once $_SERVER["DOCUMENT_ROOT"] . '/../lib/char_functions.php';


jimport( 'joomla.application.component.model' );

/**
 * ShowFull Model for Collections Component
 * 
 * @package  Guggenheim
 * @subpackage	Collections
 * @license    GNU/GPL
 * @author ID Society
 */
class CollectionsModelShowFull extends JModel {
	
	protected $DataLayer;
	
	protected $link_path;
	protected $CollectionsUtils;
	
	public $xml;
	
	protected $uri;
	protected $show_which;
	protected $page_number;
	protected $search_field;
	protected $search_value;
	protected $object_num;
	protected $total_results;
	protected $current_record;
	
	protected $search_type;
	
	protected $single_view_only;
	
	
  /**
   * CollectionsModelShowFull::__construct()
   *
   * Calls parent constructor and initiates any necessary settings
   *
   * @return void
   */
	function __construct() {
   		parent::__construct();
   		$this->DataLayer = new DataLayer();
   		
   		$this->CollectionsUtils = new CollectionsUtils();
   		$this->single_view_only = false;
   		
   	}
	
	
  /**
   * CollectionsModelShowFull::setLinkPath()
   *
   * @param string $link_path
   * @return void
   */
	function setLinkPath($link_path) {
		$this->link_path = $link_path;
	}
	
	
  /**
   * CollectionsModelShowFull::setShowWhich()
   *
   * @param string $value
   * @return void
   */
	function setShowWhich($value) {
		$this->show_which = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setSearchField()
   *
   * @param string $value
   * @return void
   */
	function setSearchField($value) {
		$this->search_field = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setSearchValue()
   *
   * @param string $value
   * @return void
   */
	function setSearchValue($value) {
		$this->search_value = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setObjectNum()
   *
   * @param int $value
   * @return void
   */
	function setObjectNum($value) {
		$this->object_num = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setURI()
   *
   * @param string $value
   * @return void
   */
	function setURI($value) {
		$this->uri = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setTotalResults()
   *
   * @param string $value
   * @return void
   */
	function setTotalResults($value) {
		$this->total_results = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setCurrentRecord()
   *
   * @param int $value
   * @return void
   */
	function setCurrentRecord($value) {
		$this->current_record = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setPageNumber()
   *
   * @param int $value
   * @return void
   */
	function setPageNumber($value) {
		$this->page_number = $value;
	}
	
	
  /**
   * CollectionsModelShowFull::setSearchType()
   *
   * @param string $value
   * @return void
   */
	function setSearchType($value) {
		$this->search_type = $value;
	}
	

  /**
   * CollectionsModelShowFull::getPieceInfo()
   *
   * Generate and run the query to get info about the requested piece
   *
   * @param int $record_to_retrieve
   * @return object
   */
	function getPieceInfo($record_to_retrieve='') {
		if (empty($record_to_retrieve)) {
			$record_to_retrieve = $this->current_record;
		}
	
		switch ($this->show_which) {
			case "piece":
			default:
				$profile = "objects";
				break;
		}

		switch ($this->search_type) {
			case '':
			case null:
			default:			
				$search_string = $this->CollectionsUtils->formatSearchString($this->search_field, $this->search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "contains", "single");
				break;
				
			case "date":
				//$this->search_value = str_replace("-", ";", $this->search_value);
				$search_value = str_replace("-", ";", $this->search_value);
				$search_string = $this->CollectionsUtils->formatSearchString($this->search_field, $search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "is between", "single");
				break;
				
			case "quicksearch":
				$search_string = $this->CollectionsUtils->formatQuickSearchString($this->search_field, $this->search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, "objects", "quicksearch", $record_to_retrieve, "single");
				break;
				
			case "exact":
			case "on-view-ny":
			case "recent-acquisition":
				$search_string = $this->CollectionsUtils->formatSearchString($this->search_field, $this->search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "is", "single");
				break;
			
			case "title":
				$this->single_view_only = true;
				if (!empty($this->object_num)) {
					$search_string = $this->CollectionsUtils->formatSearchString('Number', $this->object_num, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "is", "single");
				} else {
					$search_string = $this->CollectionsUtils->formatSearchString($this->search_field, $this->search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "contains", "single");
				}
				break;
			
			case "highlight":
				$this->single_view_only = true;
				$search_string = $this->CollectionsUtils->formatSearchString($this->search_field, $this->search_value, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, $profile, "advsearch", $record_to_retrieve, "is", "single", "1");
				break;
		}
		
		
		return $this->CollectionsUtils->doSearch($search_string);
	}


  /**
   * CollectionsModelShowFull::outputPieceResults()
   *
   * Output the needed information about the selected piece
   *
   * @param object $eMuseumResults
   * @return object
   */
	function outputPieceResults($eMuseumResults='') {
		//print_r($eMuseumResults);
		//die;
		$total_results = $eMuseumResults->result["total"];
		$this->setTotalResults($total_results);
		$result->total_results = makeSafeEntities($total_results);
		
		$result->single_view_only = $this->single_view_only;
		$result->page_number = $this->page_number;
		$result->search_field = $this->search_field;
		$result->current_record = $this->current_record;
		
		$artist_name = makeSafeEntities($eMuseumResults->result->object->people["displayname"]);
		$result->artist_name = makeSafeEntities($eMuseumResults->result->object->people["displayname"]);
		$result->title = makeSafeEntities($eMuseumResults->result->object["title"], 1);
		$result->stripped_title = strip_tags(makeSafeEntities($eMuseumResults->result->object["title"], 2));
		$result->preview_image = $eMuseumResults->result->object["previewfile"];
		$fullsize_image = $eMuseumResults->result->object["fullfile"];
		$result->fullsize_image = $eMuseumResults->result->object["fullfile"];
		$result->thumbs = $this->generateThumbs($eMuseumResults);
		$result->essay = makeSafeEntities($this->CollectionsUtils->standardize($eMuseumResults->result->object->essay["essay"]));
		
		$raw_caption = $eMuseumResults->result->object->caption;
		$result->caption = makeSafeEntities($this->formatCaption($raw_caption));
		


		// Generate the string that will be used in the browser title.
		// Format: Artist Name. Artwork Name. Date
		$result->browser_title = '';
		if (!empty($eMuseumResults->result->object->people["displayname"])) {
			$result->browser_title .= $eMuseumResults->result->object->people["displayname"];
		}
		if (!empty($eMuseumResults->result->object["title"])) {
			if (!empty($result->browser_title)) {
				if (substr($result->browser_title, -1) == '.') {
					$result->browser_title .= ' ';
				} else {
					$result->browser_title .= '. ';
				}
			}
			$result->browser_title .= $eMuseumResults->result->object["title"];
		}
		if (!empty($eMuseumResults->result->object["displaydate"])) {
			if (substr($result->browser_title, -1) == '.') {
					$result->browser_title .= ' ';
				} else {
					$result->browser_title .= '. ';
				}
			$result->browser_title .= $eMuseumResults->result->object["displaydate"];
		}
		

		// Title will not process HTML so any markup in the title 
		// needs to be removed
		$result->browser_title = strip_tags($result->browser_title);
		
		$search_value = makeSafeEntities($this->search_value);
		$result->search_value = makeSafeEntities($this->search_value);
		$result->search_value_for_link = rawurlencode(mb_convert_encoding($search_value,"UTF-8", "HTML-ENTITIES"));
		
		$artist_name_value_for_link = rawurlencode(mb_convert_encoding(makeSafeEntities($eMuseumResults->result->object->people["displayname"]),"UTF-8", "HTML-ENTITIES"));
		$more_works_by_link = JRoute::_('index.php?option=com_collections') . "/show-list/artist/" . strtolower(substr($eMuseumResults->result->object->people["alphasort"], 0, 1)) . "/?search=" . $artist_name_value_for_link;
		
		
		$result->lightbox_link = $fullsize_image . '#TB_inline?height=657&amp;width=525&amp;inlineId=full-image';
		//print_r($result);


		if ($this->hasBio($eMuseumResults->result->object->people["constituentid"])) {
			$bio_link = JRoute::_('index.php?option=com_collections') . "/show-full/bio/?artist_name=" . $artist_name_value_for_link . "&amp;page=" . $this->page_number . "&amp;f=Name" . "&amp;cr=" . $this->current_record;
			$result->bio_link = '<a href="' . $bio_link . '">Biography</a></div>';
		} else {
			$result->bio_link = '';
		}
		
		
		$result->artist_date = $eMuseumResults->result->object->people["displaydate"];
		$result->insitution = '';
		
		foreach ($eMuseumResults->result->object->institution as $institution_result) {
			$institution_style = '';
			switch ($institution_result["institution"]) {
				case 'Solomon R. Guggenheim Museum':
					$institution_style = 'location-new-york';
					break;
				
				case 'Peggy Guggenheim Collection':
					$institution_style = 'location-venice';
					break;
				
				case 'Guggenheim Museum Bilbao':
					$institution_style = 'location-bilbao';
					break;
				
				case 'Deutsche Guggenheim Berlin':
					$institution_style = 'location-berlin';
					break;
			}
			
			$result->insitution .= '<span class="'.$institution_style.'">&nbsp;</span>';	
		}
		
		if ($total_results > 1) {
			$result->more = 'Other ' . $this->determineMore($eMuseumResults) . ' Works';
		} else {
			$result->more = '';
		}

		// Find out how many works by this artist are in the collection
		$result->artist_works_num = $this->getArtistWorksCount($eMuseumResults->result->object->people["displayname"]);
		
		// Don't show More Works By if we're in artist browse or
		// if there is only one work by this artist
		if (($this->search_field != 'People') && ($result->artist_works_num > 1)) {
			$result->more_works = '<a href="' . $more_works_by_link . '">' . 'More Works By ' . $artist_name . '</a>';
		} else {
			$result->more_works = '';
		}
		
		return $result;
	
	}
	
	
  /**
   * CollectionsModelShowFull::formatCaption()
   *
   * Generates the proper caption for the image
   *
   * @param array $raw_caption
   * @return string
   */
	function formatCaption($raw_caption) {
		$caption = "";
		$prefix = "";
		$suffix = "";
		$secondary_title = "";

		
		if (!empty($raw_caption["primarytitle"])) {
			$caption = $caption . "<em>" . $raw_caption["primarytitle"] . "</em>"; 
		}
		
		if ((!empty($raw_caption["prefix"])) || (!empty($raw_caption["suffix"])) || (!empty($raw_caption["secondtitle"]))) {
			$prefix = $prefix . " (";
			if (!empty($raw_caption["prefix"])) {
				$prefix = $prefix . $raw_caption["prefix"] . " "; 
			}
			
			if (!empty($raw_caption["suffix"])) {
				$suffix = $suffix . " " . $raw_caption["suffix"]; 
			}
			
			$suffix = $suffix . ")";
		}
		
		if (!empty($raw_caption["secondtitle"])) {
			$secondary_title = $secondary_title . "<em>" . $raw_caption["secondtitle"] . "</em>"; 
		}
		
		$caption = $caption . $prefix . $secondary_title . $suffix;
		
		if (!empty($raw_caption["displaydate"])) {
			$caption = $caption . ", " . $raw_caption["displaydate"] . ". "; 
		}
		
		if (!empty($raw_caption["medium"])) {
			$caption = $caption . " " . $raw_caption["medium"] . ", "; 
		}
		
		if (!empty($raw_caption["edition"])) {
			$caption = $caption . " " . $raw_caption["edition"] . ", "; 
		}
		
		if (!empty($raw_caption["dimensions"])) {
			$caption = $caption . " " . $raw_caption["dimensions"]; 
		}
		
		if ((!empty($raw_caption["medium"])) || (!empty($raw_caption["edition"])) || (!empty($raw_caption["dimensions"]))) {
			$caption = $caption . ". "; 
		}
		
		//cjb - added single space at the end of credit line - 3/27/09
		if (!empty($raw_caption["creditline"])) {
			$caption = $caption . " " . $raw_caption["creditline"] . "&nbsp;"; 
		}
		
		if (!empty($raw_caption["objectnumber"])) {
			$caption = $caption . " " . $raw_caption["objectnumber"]; 
		}
		
		//only add a period if the above are not empty AND it's not the last item
		if ((!empty($raw_caption["creditline"])) || (!empty($raw_caption["objectnumber"]))) {
			if ((!empty($raw_caption["copyright"])) || (!empty($raw_caption["photocredit"]))) {
				$caption = $caption . ". "; 
			}
		}
	
		if (!empty($raw_caption["copyright"])) {
			$caption = $caption . " " . $raw_caption["copyright"]; 
		}
		
		if ((!empty($raw_caption["copyright"])) && (!empty($raw_caption["photocredit"]))) {
			$caption = $caption . ". "; 
		}
		
		
		if (!empty($raw_caption["photocredit"])) {
			$caption = $caption . " " . $raw_caption["photocredit"]; 
		}
		
		return $caption;
	}
	
	
  /**
   * CollectionsModelShowFull::generateThumbs()
   *
   * Generates the output for the back/next thumbnails
   *
   * @param object $eMuseumResults
   * @return string
   */
	function generateThumbs($eMuseumResults) {
		$search_value = makeSafeEntities($this->search_value);
		$search_value_for_link = rawurlencode(mb_convert_encoding($search_value,"UTF-8", "HTML-ENTITIES"));
		$html = "";
		
		if (($this->current_record != 1) && ($this->current_record != $this->total_results)) {
			$pipe = "|";
		} else {
			$pipe = "";
		}
		
		if ($this->current_record != 1) {
			if (($this->current_record % 9) == 1) {
				$page_number = $this->page_number - 1;
			} else {
				$page_number = $this->page_number;
			}
			
			$link = $this->link_path . G_COLLECTIONS_BASE . "/show-full/piece/?search=" . $search_value_for_link 
					. "&amp;page=" . $page_number . "&amp;f=" . $this->search_field . "&amp;cr=" 
					. ($this->current_record - 1);
			$prev_piece_xml = $this->getPieceInfo(($this->current_record) - 1);
			$prev_piece = new SimpleXMLElement($prev_piece_xml);
			$postage_image = $prev_piece->result->object["postagefile"];
			$title = makeSafeEntities($prev_piece->result->object["title"], 1);
			$title_stripped = strip_tags($prev_piece->result->object["title"]);
		
			$html = $html . '<div id="collections-previous"><div id="collections-thumb-previous"><a href="' 
					. $link . '"><img src="' . $postage_image . '" alt="' . $title_stripped . '" title="' 
					. $title_stripped . '" /></a></div><a href="' . $link . '">Previous</a></div>';
		} else {
			$html = $html . '<div id="collections-previous"><div id="collections-thumb-previous"></div></div>';
		}
		
			$html = $html . '<div id="collections-pipe"><div>' . $pipe . '</div></div>';
		
		if ($this->current_record != $this->total_results) {
			if (($this->current_record % 9) == 0) {
				$page_number = $this->page_number + 1;
			} else {
				$page_number = $this->page_number;
			}
				$link = $this->link_path . G_COLLECTIONS_BASE . "/show-full/piece/?search=" . $search_value_for_link . "&amp;page=" . $page_number . "&amp;f=" . $this->search_field . "&amp;cr=" . ($this->current_record + 1);
				$next_piece_xml = $this->getPieceInfo(($this->current_record) + 1);
				$next_piece = new SimpleXMLElement($next_piece_xml);
				$postage_image = $next_piece->result->object["postagefile"];
				$title = makeSafeEntities($next_piece->result->object["title"], 1);
				$title_stripped = strip_tags($next_piece->result->object["title"]);
				
				$html = $html . '<div id="collections-next"><div id="collections-thumb-next"><a href="' 
						. $link . '"><img src="' . $postage_image . '" alt="' . $title_stripped 
						. '" title="' . $title_stripped . '" /></a></div><a href="' . $link 
						. '">Next</a></div>';
		} else {
			$html = $html . '<div id="collections-next"><div id="collections-thumb-next"></div></div>';
		}

		return $html;
	}
		
		
  /**
   * CollectionsModelShowFull::outputPieceHTMLChunk()
   *
   * @param object $eMuseumResults
   * @return string
   */
	function outputPieceHTMLChunk($eMuseumResults='') {
		$total_results = $eMuseumResults->result["total"];
		$this->setTotalResults($total_results);
		$artist_name = makeSafeEntities($eMuseumResults->result->object->people["displayname"]);
		$title = strip_tags(makeSafeEntities($eMuseumResults->result->object["title"], 2));
		$fullsize_image = $eMuseumResults->result->object["fullfile"];
		$raw_caption = $eMuseumResults->result->object->caption;
		$caption = makeSafeEntities($this->formatCaption($raw_caption));
	
		$html = "";
		
		//hidden inline content for lightbox
		$html .= '<h2 id="image-artist-name">' . $artist_name . '</h2>';
		$html .= '<img id="full-image-img" src="' . $fullsize_image . '" alt="' . $title . '" title="' . $title . '" />';
		$html .= '<p id="image-caption">' . $caption . '</p>';
		

		return $html;
	
	}
	
	
  /**
   * CollectionsModelShowFull::hasBio()
   *
   * Checks the eMuseum database to see whethere there is a bio 
   * for this artist.
   *
   * @param int $consituent_id
   * @return bool
   */
	function hasBio($consituent_id) {
		$query = "SELECT Biography FROM emu_People WHERE ConstituentID = " . $consituent_id;
		//$bio = array_pop(array_pop($this->DataLayer->runSelectQuery($query, "array", MDB2_FETCHMODE_ORDERED)));
		$results = $this->DataLayer->runSelectQuery($query, "array", MDB2_FETCHMODE_ORDERED);
		$bio = '';
		if (is_array($results) && (count($results) > 0)) {
			$bio = array_pop(array_pop($results));
		}
		
		if (empty($bio)) {
			return false;
		} else {
			return true;
		}
	}
	
	
  /**
   * CollectionsModelShowFull::getArtistWorksCount()
   *
   * Does a query of the eMuseum database to find out how many 
   * works there are by the selected artist
   *
   * @param string $artist_name
   * @return int $num_results
   */
	function getArtistWorksCount($artist_name) {
		$artist_name_for_search = mb_convert_encoding(makeSafeEntities($artist_name),"UTF-8", "HTML-ENTITIES");
		
		$search_string = $this->CollectionsUtils->formatSearchString("People", $artist_name_for_search, G_EMUSEUM_ROOT_URL . G_EMUSEUM_CODE, "objects", "advsearch", 1);
		$search_results_xml = $this->CollectionsUtils->doSearch($search_string);
		
		$search_results_array = new SimpleXMLElement($search_results_xml);
		$num_results = $search_results_array->result["total"];
		
		return $num_results;
	}
	
	
  /**
   * CollectionsModelShowFull::determineMore()
   *
   * @param object $eMuseumResults
   * @return string
   */
	function determineMore($eMuseumResults='') {
		switch ($this->search_field) {
			case "People":
			default:
				return makeSafeEntities($eMuseumResults->result->object->people["lastname"]);
				break;	
				
			case "Artwork Type":
			case "Institution":
				return makeSafeEntities($this->search_value);
				break;	
				
			case "Date":
				$value = str_replace(";", "-", $this->search_value);
				return makeSafeEntities($value);
				break;		
				
			case "Movement":
				$abbrv = $this->getCorrectAbbrv($eMuseumResults, 'movement', 'term');
				
				return makeSafeEntities($abbrv);
				break;	
			
			case "Major Acquisition":
				return makeSafeEntities($eMuseumResults->result->object->acquisitions["abbrv"]);
				break;
				
			case "Works on View":
			case "Recent Acquisition":
				return makeSafeEntities($this->search_field);
				break;		
				
			case "quicksearch":
				return '"' . makeSafeEntities($this->search_value) . '"';
				break;	
		}
		
	}
	
	
	
  /**
   * CollectionsModelShowFull::getCorrectAbbrv()
   *
   * Find the first instance of the abbreviation that corresponds to the 
   * selected sort/browse. This function is needed because many objects 
   * are tagged with multiple values per attribute.
   *
   * @param object $eMuseumResults
   * @param string $node_name
   * @param string $attribute_name
   * @return string $blurb
   */
	function getCorrectAbbrv($eMuseumResults, $node_name, $attribute_name) {
		$blurb = '';
		
		for ($i = 0; $i < count($eMuseumResults->result->object); $i++) {
			$node_array = $eMuseumResults->result->object[$i]->$node_name;
			
			for ($j = 0; $j < count($node_array); $j++) {
				if ($node_array[$j]["$attribute_name"] == $this->search_value) {
					$blurb = $node_array[$j]["abbrv"];
					break 2;
				}
			}
		}
		
		return $blurb;
	}
	
}

?>